package leetcode;

import java.util.HashMap;

public class LengthOfLongestSubstring {
    public static int lengthOfLongestSubstring(String s) {
/*        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0, start = 0;
        for (int end = 0; end < s.length(); end++) {
            char ch = s.charAt(end);
            if (map.containsKey(ch)){
                start = Math.max(map.get(ch)+1,start);
            }
            max = Math.max(max,end - start + 1);
            map.put(ch,end);//重复的会覆盖
        }
        return max;*/

        HashMap<Character, Integer> map = new HashMap<>();//用map存储字符对应索引
        int max = 0, start = 0;//存储开始索引位置
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)){
                start = Math.max(map.get(c) +1,start); //更新开始位置索引
            }
            max = Math.max(max,i - start +1);
            map.put(c,i);
        }
        return max;
    }
}
